<?php

/*
Plugin Name: 文章更新推送
Description: 通过Webhook方式，将文章更新通知推送到Webhook
Version: 1.1.0
Author: 孙子烧烤
Author URI: https://www.sunzishaokao.com/author/1
Plugin URI: https://www.sunzishaokao.com/
*/

// 添加一个设置页面
function auto_post_webhook_settings_init() {
    // 注册一个设置段，用于存储Webhook URL
    register_setting('reading', 'auto_post_webhook_url');

    // 添加一个设置字段到阅读设置页面
    add_settings_field(
        'auto_post_webhook_url',
        'Webhook URL',
        'auto_post_webhook_url_html',
        'reading',
        'default'
    );
}

add_action('admin_init', 'auto_post_webhook_settings_init');

// 输出Webhook URL的HTML输入框
function auto_post_webhook_url_html() {
    $value = get_option('auto_post_webhook_url', '');
    echo '<input type="text" id="auto_post_webhook_url" name="auto_post_webhook_url" value="' . esc_attr($value) . '" class="regular-text ltr"/>';
}

// Hook into the post status transition actions
add_action('transition_post_status', 'auto_post_webhook_on_status_change', 10, 3);

function auto_post_webhook_on_status_change($new_status,$old_status, $post) {
    // Only trigger webhook on 'publish' and when not a revision or autosave
    if (
        $new_status === 'publish' && 
        $old_status !== 'publish' && 
        !wp_is_post_revision($post) && 
        !wp_is_post_autosave($post)
    ) {
        send_auto_post_webhook($post);
    }
}

// Prevent the webhook from firing during deletion
add_action('before_delete_post', 'prevent_webhook_on_delete');

function prevent_webhook_on_delete($post_id) {
    // Remove the transition_post_status action to prevent webhook on delete
    remove_action('transition_post_status', 'auto_post_webhook_on_status_change', 10);
}

function send_auto_post_webhook($post) {
    // Get the necessary data
    $author_id =$post->post_author;
    $author_name = get_the_author_meta('display_name',$author_id);
    $categories = get_the_category($post->ID);
    $category_names = implode(', ', wp_list_pluck($categories, 'name'));
    
    // 修改文章摘要为从文章内容提取前25个字符
    $excerpt_length = 50;
    $article_excerpt = wp_strip_all_tags($post->post_content);
    $short_excerpt = mb_strimwidth($article_excerpt, 0, $excerpt_length, '...');

    // 获取站点URL
    $site_url = get_bloginfo('url');
    $site_name = get_bloginfo('name');

    // Prepare the message content with the correct permalink format
    $message = "{$site_name}文章更新啦！[CQ:face,id=99]\n文章标题：{$post->post_title}\n文章作者：{$author_name}\n文章分类：$category_names\n文章摘要：$short_excerpt\n文章链接:{$site_url}/{$post->ID}.html";

    // Prepare the data to be sent in the format expected by the webhook
    $data = array(
        'message' => $message,
    );

    // Encode the data as JSON
    $json_data = json_encode($data);

    // Get the Webhook URL from the settings
    $webhook_url = get_option('auto_post_webhook_url', '');

    // Set up the headers
    $headers = array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json_data),
    );

    // Initialize a cURL session
    $ch = curl_init($webhook_url);

    // Set the cURL options
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS,$json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);

    // Execute the cURL session
    $response = curl_exec($ch);

    // Check for errors
    if (curl_errno($ch)) {
        error_log('cURL error: ' . curl_error($ch));
    } else {
        // Check the HTTP response code
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code != 200) {
            error_log("Webhook request returned HTTP code $http_code");
        }
    }

    // Close the cURL session
    curl_close($ch);
}
